<template>
  <el-dialog v-model="dialogVisible" title="发布学习课程" @open="onDialogOpen" @close="onDialogClose">
    <el-form ref="courseForm" :model="form" :rules="rules" label-width="120px" label-position="top" style="padding: 20px">
       <el-row :gutter="10">
         <el-col :span="12">
           <el-form-item label="课程标题" prop="StudyCourseName">
             <el-input v-model="form.StudyCourseName" placeholder="请输入课程标题" clearable/>
           </el-form-item>
           <el-row :gutter="10">
             <el-col :span="12">
               <el-form-item label="发布时间" prop="StudyCourseStartTime">
                 <el-date-picker type="datetime" v-model="form.StudyCourseStartTime" placeholder="选择发布时间" style="width: 100%"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" />
               </el-form-item>
             </el-col>
             <el-col :span="12">
               <el-form-item label="截止时间" prop="StudyCourseEndTime">
                 <el-date-picker type="datetime" v-model="form.StudyCourseEndTime" placeholder="选择截止时间" style="width: 100%"  value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss" />
               </el-form-item>
             </el-col>
           </el-row>
         </el-col>
         <el-col :span="12">
           <el-form-item label="课后思考" prop="StudyCourseTile">
             <el-input v-model="form.StudyCourseTile" type="textarea" :rows="5" placeholder="请输入课后思考题目，例如：
1. 如何理解党的二十大对全面建设社会主义现代化国家作出的战略部署？
2. 中国式现代化的本质要求有哪些？
3. 如何在本职工作中更好地贯彻落实党的二十大精神？"
             />
           </el-form-item>
         </el-col>
       </el-row>

      <!-- 课程章节 -->
      <el-form-item label="课程章节" style="font-weight: bolder" prop="chapters">
        <div class="chapter-container flex flex-wrap justify-content-space-between" style="width: 100%">
          <div v-for="(chapter, index) in form.chapters" :key="index" class="chapter-item " style="width: 49%">
            <div class="chapter-header">
              <span class="chapter-number">{{ index + 1 }}</span>
              <div  style="flex: 1; margin-left: 5px; border: 2px solid #eae8e8; padding: 0px 10px;border-radius:5px">党的二十大报告解读与研究</div>
              <el-button type="primary" plain @click="removeChapter(index)" style="margin-left: 10px;">删除</el-button>
            </div>
            <div class="chapter-content">
              <div class="upload-area">
                <el-upload
                    v-model:file-list="chapter.files"
                    action="#"
                    :auto-upload="false"
                    :limit="1"
                    accept=".pdf,.doc,.docx,.ppt,.pptx"
                    :on-change="handleFileChange"
                    :on-remove="handleFileRemove"
                    :before-upload="beforeUpload"
                    :on-success="handleSuccess"
                    :on-error="handleError"
                    show-file-list
                    list-type="text"
                >
                  <div class="upload-btn">
                    <el-icon><Upload /></el-icon>
                    <p>点击或拖拽文件上传</p>
                    <p style="font-size: 12px; color: #999;">支持 PDF、Word、PPT 等格式</p>
                  </div>
                </el-upload>
              </div>
              <div v-if="chapter.files.length > 0" class="file-info flex align-end" >
                <div style="width: 100%">
                  <div class="file-item" style="width: 100%">
                    <el-icon><Document /></el-icon>
                    <div>{{ chapter.files[0].name }}</div>
                    <div class="flex align-center  " style="width: 100%">
                      <div class="file-size">{{ formatFileSize(chapter.files[0].size) }}</div>
                      <div class="file-time">上传于 {{ new Date().toLocaleDateString() }}</div>
                    </div>
                  </div>
                  <div class="reading-time">
                    <el-icon style="font-size: 18px;margin-right: 5px"><Clock /></el-icon>
                    <span>预计阅读时长：{{ chapter.readingTime }} 分钟</span>
                  </div>
                </div>
                <el-button type="primary" size="small">章节预览</el-button>
              </div>
            </div>
          </div>
        </div>
       <div>
       </div>
      </el-form-item>

     <div class="flex justify-content-center">
       <el-button type="primary" plain icon="Plus" @click="addChapter" style="margin-top: 10px;">添加章节</el-button>
     </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存课程</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Document, Clock } from '@element-plus/icons-vue'
import {createStudyCourse} from "@/api/education/education.js";
// 弹窗显示状态
const dialogVisible = ref(false)
// 表单数据
const form = ref({
  StudyCourseName: '', // 课程名称
  StudyCourseStartTime: '',  // 开始时间
  StudyCourseEndTime: '',  // 结束时间
  StudyCourseTile: '',  // 课后思想
  PredictTime:25,  // 预估时间
  chapters: [
    {
      title: '',
      files: [],
      readingTime: '25'
    }
  ]
})

// 表单验证规则
const rules = {
  StudyCourseName: [
    { required: true, message: '请输入课程标题', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  StudyCourseStartTime: [
    { required: true, message: '请选择发布时间', trigger: 'change' }
  ],
  StudyCourseEndTime: [
    { required: true, message: '请选择截止时间', trigger: 'change' }
  ],
  StudyCourseTile: [
    { required: true, message: '请输入课后思考题目', trigger: 'blur' }
  ],
}

// 表单引用
const courseForm = ref(null)

// 打开弹窗时的处理
const onDialogOpen = () => {
  // 重置表单
  resetForm()
}

// 关闭弹窗时的处理
const onDialogClose = () => {
  // 清空表单
  resetForm()
}

// 重置表单方法
const resetForm = () => {
  if (courseForm.value) {
    courseForm.value.resetFields()
  }
  // 重置章节数据
  form.value.chapters = [
    {
      title: '',
      files: [],
      readingTime: '25'
    }
  ]
}

// 添加章节
const addChapter = () => {
  form.value.chapters.push({
    title: '',
    files: [],
    readingTime: '25'
  })
}

// 删除章节
const removeChapter = (index) => {
  if (form.value.chapters.length <= 1) {
    ElMessage.warning('至少需要保留一个章节')
    return
  }
  form.value.chapters.splice(index, 1)
}

// 文件上传前处理
const beforeUpload = (file) => {
  const validTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation']
  if (!validTypes.includes(file.type)) {
    ElMessage.error('不支持的文件类型，请上传PDF、Word或PPT文件')
    return false
  }
  return true
}

// 处理文件上传成功
const handleSuccess = (response, file, fileList) => {
  // 这里可以处理上传成功的逻辑
  console.log('文件上传成功:', file)
}

// 处理文件上传失败
const handleError = (error, file, fileList) => {
  ElMessage.error('文件上传失败，请重试')
}

// 处理文件变化
const handleFileChange = (file, fileList) => {
  // 更新文件列表
  form.value.chapters[fileList[0].index].files = fileList
}

// 处理文件移除
const handleFileRemove = (file, fileList) => {
  // 移除文件
  form.value.chapters[file.index].files = []
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (size < 1024) {
    return `${size} B`
  } else if (size < 1024 * 1024) {
    return `${(size / 1024).toFixed(1)} KB`
  } else {
    return `${(size / (1024 * 1024)).toFixed(1)} MB`
  }
}

// 提交表单
const submitForm = () => {
  courseForm.value.validate(async (valid) => {
    if (valid) {
      const params = {
        StudyCourseName: form.value.StudyCourseName, // 课程名称
        StudyCourseStartTime: form.value.StudyCourseStartTime,  // 开始时间
        StudyCourseEndTime:  form.value.StudyCourseEndTime,  // 结束时间
        StudyCourseTile:  form.value.StudyCourseTile,  // 课后思想
        PredictTime: form.value.PredictTime,  // 预估时间
      }
      let formData = new FormData();
      formData.append("StudyCourseName", params.StudyCourseName);
      formData.append("StudyCourseStartTime", params.StudyCourseStartTime);
      formData.append("StudyCourseEndTime", params.StudyCourseEndTime);
      formData.append("StudyCourseTile", params.StudyCourseTile);
      formData.append("PredictTime", params.PredictTime);
      let result = await createStudyCourse(formData);
      let data = result.data.data;
      if (result.status == 200 && result.data.code == 200) {
        ElMessage.success('课程保存成功！');
        dialogVisible.value = false;
      }else {
        ElMessage.error(result.data.msg);
      }
    } else {
      ElMessage.error('请检查表单填写是否正确')
    }
  })
}

// 暴露方法供外部调用
defineExpose({
  open: () => {
    dialogVisible.value = true
  },
  close: () => {
    dialogVisible.value = false
  }
})
</script>

<style scoped lang="scss">
.chapter-container {
  margin-top: 20px;
}

.chapter-item {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
  background-color: #fff;
}

.chapter-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.chapter-number {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #f56c6c;
  color: white;
  border-radius: 50%;
  font-weight: bold;
  margin-right: 10px;
}

.upload-area {
  border: 2px dashed #dcdfe6;
  border-radius: 4px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  &:hover {
    border-color: #409eff;
    background-color: #f5f7fa;
  }
}

.upload-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  cursor: pointer;
}

.file-info {
  margin-top: 16px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.file-item {
  margin-bottom: 8px;
}

.file-size {
  margin-left: 8px;
  color: #999;
  font-size: 12px;
}

.file-time {
  margin-left: 8px;
  color: #999;
  font-size: 12px;
}

.reading-time {
  display: flex;
  align-items: center;
  margin-top: 8px;
  color: #666;
  font-size: 12px;
}

.dialog-footer {
  text-align: right;
}
</style>
